package com.learner.ucenter.service.impl;


import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.learner.common.exception.ExceptionUtil;
import com.learner.common.exception.RestException;
import com.learner.common.util.FormUtils;
import com.learner.ucenter.handle.SmsProperties;
import com.learner.ucenter.service.MsmService;
import com.learner.ucenter.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author ice2020x
 * @Date: 2023/2/25
 * @Description: 发送短信的类
 **/
@Service
@Slf4j
public class MsmServiceImpl implements MsmService {

    @Autowired
    SmsProperties smsProperties;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendMsg(HttpServletRequest request, String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw ExceptionUtil.createException(RestException.class, 1000002);
        } else if (!FormUtils.isMobile(phone)) {
            throw ExceptionUtil.createException(RestException.class, 1000001);
        }
        sendSms(phone);
    }

    /**
     * 发送短信
     *
     * @param phoneNumber username
     * @return 结果
     */
    private void sendSms(String phoneNumber) {
        // 短信应用SDK AppID  1400开头
        int appid = smsProperties.getAppid();
        // 短信应用SDK AppKey
        String appKey = smsProperties.getAppkey();
        // 短信模板ID，需要在短信应用中申请
        int templateId = smsProperties.getTemplateId();

        // 签名，使用的是签名内容，而不是签名ID
        String smsSign = smsProperties.getSmsSign();
        //随机生成六位验证码的工具类
        String code = RandomUtil.getSixBitRandom();
        redisTemplate.opsForValue().set(phoneNumber, code, 5, TimeUnit.MINUTES);
        System.out.println("验证码：" + code);
        try {
            //参数，一定要对应短信模板中的参数顺序和个数，
            String[] params = {code, "3"};
            //创建sender对象
            SmsSingleSender sender = new SmsSingleSender(appid, appKey);

            //发送
            SmsSingleSenderResult result = sender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");
            if (result.result != 0) {
                throw ExceptionUtil.createException(RestException.class, 1000019);
            }
        } catch (HTTPException e) {
            log.error("HTTP响应码错误，错误是:", e);
        } catch (JSONException e) {
            log.error("json解析错误，错误是:", e);
        } catch (Exception e) {
            log.error("网络IO错误，错误是:", e);
        }
    }
}
